package cn.edu.ujn.food.controller;

import cn.edu.ujn.food.entity.*;
import cn.edu.ujn.food.service.*;
import cn.edu.ujn.util.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@org.springframework.stereotype.Controller
public class CouponController {
    @Autowired
    private UserService userService;
    @Autowired
    private CouponService couponService;

    @GetMapping("/coupon/{id}")
    @ResponseBody
    public ResponseEntity<Coupon> getCouponById(@PathVariable("id") Integer couponId) {
        Coupon coupon = couponService.queryById(couponId);
        if (coupon == null) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity<>(coupon, HttpStatus.OK);
    }

    @PutMapping("/coupon/{id}")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> updateCoupon(@PathVariable("id") Integer couponId, @RequestBody Coupon coupon) {
        try {
            coupon.setCouponId(couponId);
            couponService.update(coupon);
            return ResponseEntity.ok(Map.of("success", true, "message", "优惠券信息已成功更新"));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("success", false, "message", "更新失败: " + e.getMessage()));
        }
    }

    @DeleteMapping("/coupon/{id}")
    public ResponseEntity<Map<String, Object>> deleteCoupon(@PathVariable("id") Integer couponId) {
        try {
            boolean isDeleted = couponService.deleteById(couponId);
            if (isDeleted) {
                return ResponseEntity.ok(Map.of("success", true, "message", "优惠券信息删除成功！"));
            } else {
                return new ResponseEntity<>(Map.of("success", false, "message", "优惠券信息删除失败，优惠券不存在或已删除。"), HttpStatus.NOT_FOUND);
            }
        } catch (Exception e) {
            return new ResponseEntity<>(Map.of("success", false, "message", "优惠券信息删除失败: " + e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @PostMapping("/coupon")
    @ResponseBody
    public String createCoupon(Coupon coupon) {
        try {
            couponService.insert(coupon);
            return "OK";
        } catch (Exception e) {
            return "FAIL";
        }
    }

    @GetMapping("/coupon")
    public String listCoupon(@RequestParam(value = "page", defaultValue = "1") Integer page,
                             @RequestParam(value = "row", defaultValue = "10") Integer rows, Model model, Coupon coupon) {
        coupon.setStart((page - 1) * rows);
        coupon.setRows(rows);
        Page<Coupon> page3 = couponService.selectAll(coupon);
        page3.setPage(page);
        model.addAttribute("page", page3);
        return "coupon";
    }
}


